package game.entities;

import game.gfx.Colors;
import game.gfx.Screen;
import game.level.Level;
import game.Game;
import game.InputHandler;

public class Arrow extends Projectile{

	private long timeNow = System.currentTimeMillis();
	private long timeLast = System.currentTimeMillis();
	private int calcGrav = 25;
	private InputHandler input;
	private int color = Colors.get(-1, 531, 555, 333);
	public Arrow(Level level, int vel, int ang, int x, int y, InputHandler input) {
		super(level, vel, ang, x, y, input);
		this.input = input;
	}

	public void tick() {
		timeNow = System.currentTimeMillis();
		velY++;
		timeLast = timeNow;
		move(velX,velY);
	}

	public void render(Screen screen) {
		int flipTop = 0;
		int flipBottom = 0;
		if (input.mouse.mousePosX() < 330) {
			flipTop = 1;
			flipBottom = 1;
		}
		int xTile = 10;
		int yTile = 20;
		int modifier = 8 * scale;
		int xOffset = x - modifier / 2;
		int yOffset = y - modifier / 2 - 4;
		screen.render(xOffset + modifier - (modifier * flipTop), yOffset, xTile	+ 1 + yTile * 32, color, flipTop, scale);
		screen.render(xOffset + (modifier * flipTop), yOffset, (xTile) + yTile * 32, color, flipTop, scale);
		screen.render(xOffset + modifier - (modifier * flipBottom), yOffset + modifier, xTile + 1 + (yTile + 1) * 32, color, flipBottom, scale);
		screen.render(xOffset + (modifier * flipBottom), yOffset + modifier, (xTile) + (yTile + 1) * 32, color, flipBottom, scale);
		if(hasCollided(velX,velY)){
			level.removeEntity(this);
		}
		Hostile h = hasStruck();
		if(h != null){
			h.takeDamage((int)Math.sqrt(Math.abs(Math.pow(velX, 3)) + Math.abs(Math.pow(velY, 3))));
			level.removeEntity(this);
			if(h.health<=0){
				level.removeEntity(h);
			}
		}
	}
	
	public boolean hasCollided(int xa, int ya) {
		int xMin = -7;
		int xMax = 7;
		int yMin = -1;
		int yMax = 1;
		for (int x = xMin; x < xMax; x++) {
			if (isSolidTile(xa, ya, x, yMin)) {
				return true;
			}
		}
		for (int x = xMin; x < xMax; x++) {
			if (isSolidTile(xa, ya, x, yMax)) {
				return true;
			}
		}		for (int y = yMin; y < yMax; y++) {
			if (isSolidTile(xa, ya, xMin, y)) {
				return true;
			}
		}
		for (int y = yMin; y < yMax; y++) {
			if (isSolidTile(xa, ya, xMax, y)) {
				return true;
			}
		}
		return false;
	}
	
	public Hostile hasStruck() {
		//System.out.println("SWING");
		for (Entity e : level.getEntities()) {
			if (e.hasHitbox && e.isEnemy) {
				for (int arrowX = this.x -6; arrowX <= this.x + 6; arrowX++) {
					int arrowY = this.y - 1;
					if (arrowX <= e.x + 5 * Game.SCALE
							&& arrowX >= e.x
							&& arrowY >= e.y
							&& arrowY <= e.y + 15 * Game.SCALE) {
						return (Hostile)e;
					}
					arrowY = this.y + 1;
					if (arrowX <= e.x + 5 * Game.SCALE
							&& arrowX >= e.x
							&& arrowY >= e.y
							&& arrowY <= e.y + 15 * Game.SCALE) {
						return (Hostile)e;
					}
				}
			}
		}
		return null;
	}

}
